package com.itjin.resume_back.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itjin.resume_back.entity.Project;
import com.itjin.resume_back.mapper.ProjectMapper;
import com.itjin.resume_back.service.ProjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

  private final ObjectMapper objectMapper = new ObjectMapper();

  @Value("${file.upload-dir}")
  private String uploadDir;

  @Override
  public void createProject(Long userId, String name, String description, String techStack, MultipartFile file)
      throws IOException {
    // 验证文件
    if (file == null || file.isEmpty()) {
      throw new IllegalArgumentException("项目文件不能为空");
    }

    // 创建上传目录
    Path uploadPath = Paths.get(uploadDir);
    if (!Files.exists(uploadPath)) {
      Files.createDirectories(uploadPath);
    }

    // 生成唯一文件名
    String originalFilename = file.getOriginalFilename();
    String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
    String fileName = UUID.randomUUID().toString() + fileExtension;
    Path filePath = uploadPath.resolve(fileName);

    // 保存文件
    Files.copy(file.getInputStream(), filePath);

    // 处理技术栈，确保是有效的JSON格式
    String techStackJson;
    try {
      if (techStack != null && !techStack.isEmpty()) {
        // 将逗号分隔的字符串转换为JSON数组
        List<String> techList = Arrays.asList(techStack.split(","));
        techStackJson = objectMapper.writeValueAsString(techList);
      } else {
        techStackJson = "[]";
      }
    } catch (Exception e) {
      throw new IllegalArgumentException("技术栈格式无效");
    }

    // 创建项目记录
    Project project = new Project();
    project.setUserId(userId);
    project.setName(name);
    project.setDescription(description);
    project.setTechStack(techStackJson);
    project.setFileUrl(fileName);
    project.setIsApproved(0); // 0表示待审核

    save(project);
  }

  @Override
  public void updateProject(Long id, String name, String description, String techStack, MultipartFile file)
      throws IOException {
    Project project = getById(id);
    if (project == null) {
      throw new IllegalArgumentException("项目不存在");
    }

    // 处理技术栈，确保是有效的JSON格式
    String techStackJson = project.getTechStack();
    if (techStack != null && !techStack.isEmpty()) {
      try {
        List<String> techList = Arrays.asList(techStack.split(","));
        techStackJson = objectMapper.writeValueAsString(techList);
      } catch (Exception e) {
        throw new IllegalArgumentException("技术栈格式无效");
      }
    }

    // 更新项目信息
    project.setName(name);
    project.setDescription(description);
    project.setTechStack(techStackJson);

    // 如果提供了新文件，则更新文件
    if (file != null && !file.isEmpty()) {
      // 删除旧文件
      Path oldFilePath = Paths.get(uploadDir, project.getFileUrl());
      Files.deleteIfExists(oldFilePath);

      // 保存新文件
      String originalFilename = file.getOriginalFilename();
      String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
      String fileName = UUID.randomUUID().toString() + fileExtension;
      Path filePath = Paths.get(uploadDir, fileName);
      Files.copy(file.getInputStream(), filePath);

      project.setFileUrl(fileName);
    }

    updateById(project);
  }

  @Override
  public void deleteProject(Long id) throws IOException {
    Project project = getById(id);
    if (project == null) {
      throw new IllegalArgumentException("项目不存在");
    }

    // 删除文件
    Path filePath = Paths.get(uploadDir, project.getFileUrl());
    Files.deleteIfExists(filePath);

    // 删除记录
    removeById(id);
  }

  @Override
  public byte[] getProjectFile(Long id) throws IOException {
    Project project = getById(id);
    if (project == null) {
      throw new IllegalArgumentException("项目不存在");
    }

    Path filePath = Paths.get(uploadDir, project.getFileUrl());
    return Files.readAllBytes(filePath);
  }

  @Override
  public void approveProject(Long id, Integer status) {
    Project project = getById(id);
    if (project == null) {
      throw new RuntimeException("项目不存在");
    }

    project.setIsApproved(status);
    updateById(project);
  }

  @Override
  public void incrementDownloadCount(Long id) {
    Project project = getById(id);
    if (project == null) {
      throw new RuntimeException("项目不存在");
    }

    project.setDownloadCount(project.getDownloadCount() + 1);
    updateById(project);
  }
}